package ym.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            // 第一步：获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 第二步：获取SqlSession，SqlSession对象包含所有sql命令操作
    public static SqlSession getSqlSession(){
        // 设置true自动提交事务
        return sqlSessionFactory.openSession(true);
    }

    public static SqlSession getSqlSession(boolean flag){
        // 设置true自动提交事务
        return sqlSessionFactory.openSession(flag);
    }

}
